# -*- coding: utf-8 -*-
import json
import os
from .items import ContentItem,ZonghengItem

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


class ZonghengPipeline(object):
    # def process_item(self, item, spider):
    #     return item
    def open_spider(self, spider):
        self.f = open("纵横小说.txt", "w", encoding="utf-8")

    # 处理结构化数据
    def process_item(self, item, spider):
        data = json.dumps(dict(item), ensure_ascii=False) + "\n"
        if isinstance(item,ZonghengItem):
            self.f.write(data)
        return item

    def close_spider(self, spider):
        self.f.close()


class ContentPipeline(object):
    def process_item(self, item, spider):
        if isinstance(item, ContentItem):
            book_name = item['name']
            chapter_name = item['chapter']
            if not os.path.exists(book_name):
                os.mkdir(book_name)
            content_url=book_name+"/"+chapter_name + '.txt'
            with open(content_url, "w") as f:
                f.write(item['content'])
        return item
